package com.spzx.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.security.annotation.RequiresLogin;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/alipay")
public class AlipayController extends BaseController {

    @Autowired
    private IAlipayService alipayService;

    @Autowired
    private IPaymentInfoService paymentInfoService;

    @Operation(summary = "支付宝下单")
    @RequiresLogin
    @RequestMapping("submitAlipay/{orderNo}")
    @ResponseBody
    public AjaxResult submitAlipay(@PathVariable(value = "orderNo") String orderNo) {
        //h5表单：用于打开手机支付宝，弹出支付密码框。
        String form = alipayService.submitAlipay(orderNo);
        return success(form);
    }

    //异步通知回调接口：
    @RequestMapping("callback/notify")
    @ResponseBody
    public String alipayNotify(@RequestParam Map<String, String> paramMap, HttpServletRequest request) {
        log.info("AlipayController...alipayNotify方法执行了...");
        System.out.println("=====================支付宝扣款后返回给尚品甄选后端返回的数据========================");
        System.out.println(paramMap);
        System.out.println("=====================支付宝扣款后返回给尚品甄选后端返回的数据========================");

        //1.验签：  解密密文，和原文比较，如果一致，说明数据安全；如果数据不一致，说明可能被篡改，不安全，拒绝业务逻辑处理。
        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(paramMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if(signVerified){ // true 验签成功
            String tradeStatus = paramMap.get("trade_status");
            if("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)){ //付款成功
                //咱们业务： 1.修改支付信息    2.修改订单状态    3.减库存
                paymentInfoService.updatePaymentStatus(paramMap, 2); //   payType = 2 支付宝支付     payType = 1  微信支付
                return "success" ; //业务完成后，给支付宝返回成功字符串："success"
            }else{
                return "failure" ; //给支付宝返回失败结果。
            }
        }else{ //验签失败
            return "failure" ; //给支付宝返回失败结果。
        }

    }
}